<?php
namespace app\admin\controller;
use app\common\model\OrdersItem;
use app\common\model\Orders;
use think\Validate;
use think\Db;
use think\Session;

class StockInController extends BaseController
{
    public function purchaseList()
    {
        return view();
    }
    public function handle()
    {
        $data = input('post.');
        //return $data;
        $validate = new Validate([
            ['order_item_id','require','error1'],
            ['purchase_id','require','error2'],
            ['qty','require|number|gt:0','数量必需|数量必须是数值|数量不能为 0']
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $order_qty = Db::name('orders_item')->where('id',$data['order_item_id'])->value('qty');
        $recv_qty = Db::name('stock_in')->where('purchase_id',$data['purchase_id'])->sum('qty');
        if ($recv_qty + $data['qty'] > $order_qty) {
            $this->error('到货数量不能超过订单数量');
        }

        $info = [
            'order_item_id' => $data['order_item_id'],
            'qty'           => $data['qty'],
            'remarks'       => $data['remarks'],
            'purchase_id'   => $data['purchase_id'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time()
        ]; 
        // 判断订单是否团队订单
        // $orders = Db::name('orders')->where(['order_no'=>$data['order_no']])->find();
        // if(!empty($orders['organization_id'])){
        //     $info['organization_id'] = $orders['organization_id'];
        // }
        if( Db::name('stock_in')->insert($info) ){
            //更新报单状态
            if ($recv_qty + $data['qty'] >= $order_qty) {
                Db::name('purchase')->where('id',$info['purchase_id'])->update(['status'=>3]);
            }
            //更新订单状态
            $oi_model = new OrdersItem;
            $oi_model->updateProgress($info['order_item_id']);
            
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
    public function lists()
    {
        return view();
    }
    public function getList()
    {
        $where = array_filter(input('post.'));

        if (!empty($where['cate_name'])) {
            $where['g.cate_id'] = Db::name('goods_categories')->where('name',$where['cate_name'])->value('id');
            unset($where['cate_name']);
        }
        if (!empty($where['brand_name'])) {
            $where['g.brand_id'] = Db::name('goods_brand')->where('name',$where['brand_name'])->value('id');
            unset($where['brand_name']);
        }
        if (!empty($where['acct_name'])) {
            $where['o.acct_id'] = Db::name('account')->where('true_name',$where['acct_name'])->value('id');
            unset($where['acct_name']);
        }
        if (!empty($where['stock_ids'])) {
            $where['s.id'] = ['in',$where['stock_ids']];
            unset($where['stock_ids']);
        }
        if (!empty($where['status'])) {
            $where['status'] = $where['status'][0];
        }
        // 订单号搜索
        if (!empty($where['order_no'])) {
            $order_id = Orders::where('order_no',$where['order_no'])->value('id');
            // dump($order_id );
            $order_item_ids = OrdersItem::where('order_id',$order_id)->column('id');
            // dump($order_item_ids );
            $where['order_item_id'] = ['in',$order_item_ids];
            unset($where['order_no']);
            // $where['status'] = ['in',[1,3]];
        }
        //return $where;
        $page = max(input('get.page',0),1);
        $page_size = 15;
        // 获取团队 
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['s.organization_id'] = ['in',$organization_list];
        }
        $total = Db::name('stock_in')->alias('s')
                                    ->join('__ORDERS_ITEM__ oi','s.order_item_id=oi.id')
                                    ->join('__ORDERS__ o','o.id=oi.order_id')
                                    ->join('__GOODS__ g','oi.goods_id=g.id')
                                    ->where($where)->count();
        $data = [
            'rows'      => [],
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        if ($total ==0){
            $this->success('无记录','',$data);
        }

        $rows = Db::name('stock_in')->alias('s')
                                    ->join('__ORDERS_ITEM__ oi','s.order_item_id=oi.id')
                                    ->join('__ORDERS__ o','o.id=oi.order_id')
                                    ->join('__GOODS__ g','oi.goods_id=g.id')
                                    ->where($where)
                                    ->field('s.*,g.name as goods_name,color,spec,picture as goods_pic,order_id,order_sn,progress,cust,phone,area_path,express,detail_addr')
                                    ->order('s.add_time desc')
                                    ->page($page, $page_size)
                                    ->select();

        $order_ids = array_column($rows, 'order_id');
        $orders = Db::name('orders')->where('id', 'in', $order_ids)->column('');

        $acct_ids1 = array_column($orders, 'acct_id');
        $acct_ids2 = array_column($rows, 'acct_id');
        $acct_ids = array_unique( array_merge($acct_ids1, $acct_ids2) );
        $accts = Db::name('account')->where('id', 'in', $acct_ids)->column('');
        //报单信息
        $purchase_ids = array_column($rows, 'purchase_id');
        $purchases = Db::name('purchase')->where('id', 'in', $purchase_ids)->column('');
        //报单档口信息
        $stall_ids = array_column($purchases, 'stall_id');
        $stalls = Db::name('stall')->where('id', 'in', $stall_ids)->column('');
        //已发货信息
        $stock_in_ids = array_column($rows, 'id');
        $sends = Db::name('express_item')->where('stock_in_id','in',$stock_in_ids)
                            ->field('stock_in_id,sum(qty) as send_qty')
                            ->group('stock_in_id')->select();
        $send_map = [];
        foreach ($sends as $row) {
            $send_map[$row['stock_in_id']] = $row;
        }
    
        $status_txt = [
            1   => '待发',
            2   => '已发',
        ];
        $progress_txt = OrdersItem::$progress_desc;
        foreach ($rows as $key => $row) {
            $rows[$key]['progress_txt'] = $progress_txt[$row['progress']];
            $rows[$key]['status_txt'] = $status_txt[$row['status']];
            $rows[$key]['add_day'] = date('Y-m-d', $row['add_time']);
            $rows[$key]['add_time'] = date('H:i', $row['add_time']);
            $rows[$key]['goods_pic'] = config('upload_path') . $row['goods_pic'];
            $rows[$key]['pic_tmb'] = $this->getThumb($rows[$key]['goods_pic']);
            
            $rows[$key]['acct_name'] = $accts[$row['acct_id']]['true_name'];

            // $purchase = $purchases[$row['purchase_id']];
            // $rows[$key]['stall_name'] = $stalls[$purchase['stall_id']]['name'];

            if(isset($purchases[$row['purchase_id']])){
                $purchase = $purchases[$row['purchase_id']];
                $rows[$key]['stall_name'] = $stalls[$purchase['stall_id']]['name'];
            }else{
                $rows[$key]['stall_name'] = '数据丢失';
            }
            
            $order = $orders[$row['order_id']];
            $rows[$key]['order_no'] = $order['order_no'];
            $rows[$key]['saler'] = $accts[$order['acct_id']]['true_name'];

            $rows[$key]['deliver_qty'] = empty($send_map[$row['id']]['send_qty']) ? 0 : $send_map[$row['id']]['send_qty'];
        }

        $data['rows'] = $rows;
        $this->success('获取成功','',$data);
    }
    /**
     * 删除到货记录
     */
    public function del()
    {
        $id = $this->request->param('id');
        if( Db::name('stock_in')->where('id', $id)->delete() ) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }

    }
}